'''
Created on Oct 21, 2009

@author: nash
'''
from __future__ import with_statement
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import datetime

from xml.etree import ElementTree
import gdata.calendar.service
import gdata.service
import atom.service
import gdata.calendar
import atom
import getopt
import sys
import string
import time

#!/usr/bin/python
#
# Copyright (C) 2009  Nashath Rafeeq.
#   pyUCTItimetable V.0.0.5
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


__author__ = 'nash.rafeeg@gmail.com (Nash Rafeeg)'





#init variables 
#Intakecode = "TPMF0909ITM"                       #intake code change this 
Lecturecode = "SUR"                             #uncomment this line if you want the lectures time table 
username = "sukis.time.table@gmail.com"              #calender account name 
password = ""                          #password    
Alarmoffset = 10                                  #how long befor the event before reminders come in / uses defult setting so if you want sms be sure to set it up in the web interface 
cal_client = gdata.calendar.service.CalendarService()
#url = "http://webspace.apiit.edu.my/schedule/intakeview_intake.jsp?Intake1=" + Intakecode + "&Submit=Submit&Week=" #change the intake code to get the correct time table
url = "http://webspace.apiit.edu.my/schedule/intakeview_lecturer.jsp?LectID=" + Lecturecode + "&Submit=Submit&Week="  #URL for lecturers
def build_objects(line):
        today = datetime.datetime.today()
        parts = line.split('|')                                                   #this is lot of unesswary work i know but i like it this way feel free to edit  
        times = parts[1].split(' - ')                                             #trying to find the time
        title = parts[4]                                                        
        #print title
        where = parts[2] + "\t" + parts[3]
        #print where     
        content = parts[5]
        #print content      
        #print today
        begin_str = "%s %s" % (parts[0], times[0])
        end_str = "%s %s" % (parts[0], times[1])
        begin_time = datetime.datetime.strptime(begin_str, '%a,%d-%b-%y %H:%M')   #formating the date and time 
        end_time = datetime.datetime.strptime(end_str, '%a,%d-%b-%y %H:%M')             
        print "Adding events to the calender..."
        try:
            event = cal_InsertEvent(title, content, where, scrub_time(begin_time), scrub_time(end_time), #actuall calling the method to add the event 
                                    recurrence_data=None)
        except Exception, err:
                print err 
        print "Setting the Reminders for the event" 
        try:
            _AddReminder(event, minutes=Alarmoffset)                               #set the reminders 
        except Exception, err:
            print err

def scrub_table(url):
    mech = Browser()
    page = mech.open(url)
    print "Connecting to Apiit/UCTI server... "             #this takes a while apiit server sucks donkey balls
    html = page.read()
    print "Reading html.."                                  #why  does apiit use frames again ? 
    soup = BeautifulSoup(html)
    print "scrubing html...."
    table = soup.find("table", border=1)
     
    for row in table.findAll('tr')[1:]: 
        col = row.findAll('td') 
        date = col[0].font.string 
        time = col[1].font.string 
        classroom = col[2].font.string 
        location = col[3].font.string 
        subject = col[4].font.string 
        lecturer = col[5].font.string 
        record = (date, time, classroom, location, subject, lecturer) 
        line = "|".join(record)                             #this is redunndent i know but i am just updating this for google calander
        #print line
        print "Builidng objects.."
        build_objects(line)
        # print >>timetable, "|".join(record)  
def cal_login(username, password):
    print "Authenticating..."
    try:
       # cal_client = gdata.calendar.service.CalendarService()
        cal_client.email = username
        cal_client.password = password
        cal_client.source = 'UCTI Time table scruber python by nashath rafeeg'
        cal_client.ProgrammaticLogin()
        print "Success.."
    except Exception, err:
            print str(err)
            return 0
    return 1

def cal_InsertEvent(title, content, where, start_time, end_time,
        recurrence_data=None):
    #insertion method this is lifted off google api so ask them not me 
    event = gdata.calendar.CalendarEventEntry()
    event.title = atom.Title(text=title)
    event.content = atom.Content(text=content)
    event.where.append(gdata.calendar.Where(value_string=where))

    if recurrence_data is not None:
      # Set a recurring event
      event.recurrence = gdata.calendar.Recurrence(text=recurrence_data)
    else:
      event.when.append(gdata.calendar.When(start_time=start_time,
          end_time=end_time))
    
    new_event = cal_client.InsertEvent(event,
        '/calendar/feeds/default/private/full')
    
    return new_event
def scrub_time(T):
    f_time = T.strftime('%Y-%m-%dT%H:%M:%S.000+08:00')                         #the time should confirm to RFC3339 (http://tools.ietf.org/html/rfc3339)
    #print f_time
    return f_time

     
def _AddReminder(event, minutes=Alarmoffset):
    for a_when in event.when:
      if len(a_when.reminder) > 0:
        a_when.reminder[0].minutes = minutes
      else:
        a_when.reminder.append(gdata.calendar.Reminder(minutes=minutes))

    print 'Adding %d minute reminder to event' % (minutes,)
    return cal_client.UpdateEvent(event.GetEditLink().href, event)

check_auth =cal_login(username, password)
if check_auth == 1:
    scrub_table(url)
    print "All done"
else:
    print "Error!!!... check log"  
